package com.vshop.controller.other;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.vshop.entity.comentity.UserInfoReport;
import com.vshop.entity.interfacerequest.ExceptionRequest;
import com.vshop.entity.interfacerequest.userinforeport.request.RequestUserInfoReport;
import com.vshop.entity.interfacerequest.userinforeport.request.RequestUserInfoReportData;
import com.vshop.entity.interfacerequest.userinforeport.request.RequestUserInfoReportDeviceCode;
import com.vshop.entity.interfacerequest.userinforeport.request.RequestUserInfoReportTradeData;
import com.vshop.entity.interfacerequest.userinforeport.response.ResponseUserInfoReport;
import com.vshop.entity.interfacerequest.userinforeport.response.ResponseUserInfoReportData;
import com.vshop.service.SequenceService;
import com.vshop.service.UserInfoReportService;
import com.vshop.utils.Md5Encrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 用户信息上报（用户绑定）
 *
 * @author lm
 * @date 2019/03/07
 */
@RestController
@Api(description = "用户信息上报（用户绑定）")
@Slf4j
public class UserInfoReportingController {
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private UserInfoReportService userInfoReportService;

    @CrossOrigin
    @PostMapping(value = "userInfoReport", produces = "application/json;charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "用户信息上报（用户绑定）", response = ResponseUserInfoReport.class)
    public String userInfoReport(@ApiParam @RequestBody RequestUserInfoReport request) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;

        ExceptionRequest utils = new ExceptionRequest();
        String requestStr = JSON.toJSONString(request);
        if (requestStr == null) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("【用户信息上报】请求：" + requestStr);
            RequestUserInfoReport requestPackage = JSONArray.parseObject(requestStr, RequestUserInfoReport.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                RequestUserInfoReportData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String partnerCode = requestData.getPartnerCode();
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    String version = requestData.getVersion();
                    RequestUserInfoReportTradeData requestTradeData = requestData.getTradeData();
                    //lang为空或者为null时，默认为cn
                    if (StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || lang == null || version == null || requestTradeData == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        List<RequestUserInfoReportDeviceCode> deviceCodeList = null;
                        String openId = requestTradeData.getOpenId();
                        String recipientName = requestTradeData.getRecipientName();
                        String recipientPhone = requestTradeData.getRecipientPhone();
                        String recipientAddress = requestTradeData.getRecipientAddress();
                        String recipientCompany = requestTradeData.getRecipientCompany();
                        String recipientEmail = requestTradeData.getRecipientEmail();
                        String expressType = requestTradeData.getExpressType();
                        String expressPrice = requestTradeData.getExpressPrice();

                        if (openId == null || recipientName == null || recipientPhone == null || recipientAddress == null || recipientCompany == null || recipientEmail == null || expressType == null || expressPrice == null) {
                            log.info("请求报文不合法:tradeData参数不合法");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            deviceCodeList = requestTradeData.getDeviceCodeList();
                            if (deviceCodeList == null || deviceCodeList.size() <= 0) {

                                log.info("请求报文不合法:deviceCodeList参数不合法");
                                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                                return jsonString;

                            } else {
                                for (RequestUserInfoReportDeviceCode info : deviceCodeList) {
                                    String deviceCode = info.getDeviceCode();
                                    if (deviceCode == null) {
                                        log.info("请求报文不合法:不可以没有deviceCode参数");
                                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                                        return jsonString;
                                    } else {
                                        // 将请求体json转成String// 将Str拿去计算签名
                                        String str = JSON.toJSONString(requestData);
                                        String sign = utils.calculateSignature(str);
                                        log.info("计算的签名是：" + sign);
                                        if (!requestSign.equalsIgnoreCase(sign)) {
                                            jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "签名有误，请确认签名！");
                                            return jsonString;

                                        } else {//签名验证通过
                                            // 用户上报的信息入库，先要判断一下库里面有个没有相同的信息
                                            //openId != "" 与 StringUtils.isNotBlank(openId)相同

                                            if (StringUtils.isNotBlank(openId)) {
                                                log.info("【用户信息上报】：微信用户");
                                                if (StringUtils.isNotBlank(deviceCode)) {
                                                    log.info("【用户信息上报】：微信有卡");
                                                    if (StringUtils.isNotBlank(recipientName) && StringUtils.isNotBlank(recipientPhone) && StringUtils.isNotBlank(recipientAddress) && StringUtils.isNotBlank(recipientCompany) && StringUtils.isNotBlank(recipientEmail) && StringUtils.isNotBlank(expressType) && StringUtils.isNotBlank(expressPrice)) {
                                                        log.info("【用户信息上报】：微信有卡还买卡用户");
                                                        int count = userInfoReportService.queryWeixinHavaCardAndExpressInfo(partnerCode, openId, deviceCode, recipientName, recipientPhone, recipientAddress, recipientCompany, recipientEmail, expressType, expressPrice);
                                                        if (count <= 0) {
                                                            //入库
                                                            UserInfoReport userInfoReport = new UserInfoReport();
                                                            userInfoReport.setPartnerCode(partnerCode);
                                                            userInfoReport.setOpenId(openId);
                                                            userInfoReport.setDeviceCode(deviceCode);
                                                            userInfoReport.setRecipientName(recipientName);
                                                            userInfoReport.setRecipientPhone(recipientPhone);
                                                            userInfoReport.setRecipientAddress(recipientAddress);
                                                            userInfoReport.setRecipientCompany(recipientCompany);
                                                            userInfoReport.setRecipientEmail(recipientEmail);
                                                            userInfoReport.setExpressType(expressType);
                                                            userInfoReport.setExpressPrice(expressPrice);
                                                            userInfoReportService.insertWeixinHavaCardAndExpressInfo(userInfoReport);
                                                        }


                                                    } else {
                                                        log.info("【用户信息上报】：微信有卡只买套餐");
                                                        int count = userInfoReportService.queryWeixinHavaCard(partnerCode, openId, deviceCode);
                                                        if (count <= 0) {
                                                            UserInfoReport userInfoReport = new UserInfoReport();
                                                            userInfoReport.setPartnerCode(partnerCode);
                                                            userInfoReport.setOpenId(openId);
                                                            userInfoReport.setDeviceCode(deviceCode);
                                                            userInfoReportService.insertWeixinHavaCard(userInfoReport);
                                                        }

                                                    }

                                                } else {
                                                    log.info("【用户信息上报】：微信无卡");
                                                    if (StringUtils.isNotBlank(recipientName) && StringUtils.isNotBlank(recipientPhone) && StringUtils.isNotBlank(recipientAddress) && StringUtils.isNotBlank(recipientCompany) && StringUtils.isNotBlank(recipientEmail) && StringUtils.isNotBlank(expressType) && StringUtils.isNotBlank(expressPrice)) {
                                                        log.info("【用户信息上报】：微信无卡用户买卡");
                                                        int count = userInfoReportService.queryWeixinNoCardAndExpressInfo(openId, partnerCode, recipientName, recipientPhone, recipientAddress, recipientCompany, recipientEmail, expressType, expressPrice);
                                                        if (count <= 0) {
                                                            //入库
                                                            UserInfoReport userInfoReport = new UserInfoReport();
                                                            userInfoReport.setPartnerCode(partnerCode);
                                                            userInfoReport.setOpenId(openId);
                                                            userInfoReport.setRecipientName(recipientName);
                                                            userInfoReport.setRecipientPhone(recipientPhone);
                                                            userInfoReport.setRecipientAddress(recipientAddress);
                                                            userInfoReport.setRecipientCompany(recipientCompany);
                                                            userInfoReport.setRecipientEmail(recipientEmail);
                                                            userInfoReport.setExpressType(expressType);
                                                            userInfoReport.setExpressPrice(expressPrice);
                                                            userInfoReportService.insertWeixinNoCardAndExpressInfo(userInfoReport);

                                                        }


                                                    } else {
                                                        log.info("【用户信息上报】：微信无卡也无快递信息");
                                                        int count = userInfoReportService.queryWeixinNoCard(partnerCode, openId);
                                                        if (count <= 0) {
                                                            UserInfoReport userInfoReport = new UserInfoReport();
                                                            userInfoReport.setPartnerCode(partnerCode);
                                                            userInfoReport.setOpenId(openId);
                                                            userInfoReportService.insertWeixinNoCard(userInfoReport);
                                                        }

                                                    }

                                                }

                                            } else {
                                                log.info("【用户信息上报】：WEB用户，没有openid");
                                                if (StringUtils.isNotBlank(deviceCode)) {
                                                    log.info("【用户信息上报】：WEB有卡");
                                                    if (StringUtils.isNotBlank(recipientName) && StringUtils.isNotBlank(recipientPhone) && StringUtils.isNotBlank(recipientAddress) && StringUtils.isNotBlank(recipientCompany) && StringUtils.isNotBlank(recipientEmail) && StringUtils.isNotBlank(expressType) && StringUtils.isNotBlank(expressPrice)) {
                                                        log.info("【用户信息上报】：WEB有卡还写快递信息用户");
                                                        int count = userInfoReportService.queryWebHavaCardAndExpressInfo(partnerCode, deviceCode, recipientName, recipientPhone, recipientAddress, recipientCompany, recipientEmail, expressType, expressPrice);
                                                        if (count <= 0) {
                                                            //入库
                                                            UserInfoReport userInfoReport = new UserInfoReport();
                                                            userInfoReport.setPartnerCode(partnerCode);
                                                            userInfoReport.setDeviceCode(deviceCode);
                                                            userInfoReport.setRecipientName(recipientName);
                                                            userInfoReport.setRecipientPhone(recipientPhone);
                                                            userInfoReport.setRecipientAddress(recipientAddress);
                                                            userInfoReport.setRecipientCompany(recipientCompany);
                                                            userInfoReport.setRecipientEmail(recipientEmail);
                                                            userInfoReport.setExpressType(expressType);
                                                            userInfoReport.setExpressPrice(expressPrice);
                                                            userInfoReportService.insertWebHavaCardAndExpressInfo(userInfoReport);
                                                        }

                                                    } else {
                                                        log.info("【用户信息上报】：WEB有卡无快递信息，只有deviceCode");
                                                        int count = userInfoReportService.queryWebHavaCard(partnerCode, deviceCode);
                                                        if (count <= 0) {
                                                            UserInfoReport userInfoReport = new UserInfoReport();
                                                            userInfoReport.setPartnerCode(partnerCode);
                                                            userInfoReport.setDeviceCode(deviceCode);
                                                            userInfoReportService.insertWebHavaCard(userInfoReport);
                                                        }

                                                    }


                                                } else {
                                                    log.info("【用户信息上报】：WEB无卡");
                                                    if (StringUtils.isNotBlank(recipientName) && StringUtils.isNotBlank(recipientPhone) && StringUtils.isNotBlank(recipientAddress) && StringUtils.isNotBlank(recipientCompany) && StringUtils.isNotBlank(recipientEmail) && StringUtils.isNotBlank(expressType) && StringUtils.isNotBlank(expressPrice)) {
                                                        log.info("【用户信息上报】：WEB无卡有快递信息");
                                                        int count = userInfoReportService.queryWebNoCardAndExpressInfo(partnerCode, recipientName, recipientPhone, recipientAddress, recipientCompany, recipientEmail, expressType, expressPrice);
                                                        if (count <= 0) {
                                                            //入库
                                                            UserInfoReport userInfoReport = new UserInfoReport();
                                                            userInfoReport.setPartnerCode(partnerCode);
                                                            userInfoReport.setRecipientName(recipientName);
                                                            userInfoReport.setRecipientPhone(recipientPhone);
                                                            userInfoReport.setRecipientAddress(recipientAddress);
                                                            userInfoReport.setRecipientCompany(recipientCompany);
                                                            userInfoReport.setRecipientEmail(recipientEmail);
                                                            userInfoReport.setExpressType(expressType);
                                                            userInfoReport.setExpressPrice(expressPrice);
                                                            userInfoReportService.insertWebNoCardAndExpressInfo(userInfoReport);
                                                        }

                                                    } else {
                                                        log.info("【用户信息上报】：WEB无卡无快递信息");
                                                        if (lang.equals("cn") || StringUtils.isNotBlank(lang)) {
                                                            jsonString = utils.ncompleteReporting(ConnSeqNo, curtime, tradeType, partnerCode);
                                                            return jsonString;
                                                        } else {
                                                            jsonString = utils.ncompleteReportingEN(ConnSeqNo, curtime, tradeType, partnerCode);
                                                            return jsonString;
                                                        }
                                                    }


                                                }

                                            }


                                        }

                                    }

                                }

                                //回复接口
                                ResponseUserInfoReportData data = new ResponseUserInfoReportData();
                                data.setConnSeqNo(ConnSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setTradeType(tradeType);
                                data.setTradeTime(tradeTime);
                                data.setTradeRstCode("0000");
                                if (lang.equals("cn") || StringUtils.isNotBlank(lang)) {
                                    data.setTradeRstMessage("成功");
                                } else {
                                    data.setTradeRstMessage("success");
                                }
                                ResponseUserInfoReport responseUserInfoReport = new ResponseUserInfoReport();
                                responseUserInfoReport.setData(data);
                                responseUserInfoReport.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));

                                jsonString = JSON.toJSONString(responseUserInfoReport);
                                log.info("【用户信息上报】响应：" + jsonString);
                                return jsonString;

                            }

                        }
                    }
                }
            }
        }
    }


}
